<!doctype html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>控制面板</title>
    <style>
      body { font-family: system-ui, -apple-system, Segoe UI, Roboto, Arial, sans-serif; padding: 24px; }
      .card { max-width: 560px; border: 1px solid #ddd; border-radius: 8px; padding: 16px; }
      .row { display: flex; gap: 12px; margin-top: 12px; }
      button { padding: 10px 16px; border-radius: 6px; border: 1px solid #999; cursor: pointer; }
      button:hover { background: #f5f5f5; }
      .status { margin-top: 12px; color: #555; }
      .hint { margin-top: 8px; font-size: 13px; color: #777; }
    </style>
  </head>
  <body>
    <div class="card">
      <h2>控制面板</h2>
      <p>点击按钮向所有已连接的客户端发送指令。</p>

      <div class="row">
        <button id="btnGet">获取所有金额</button>
        <button id="flashPage">刷新页面数据</button>
      </div>

      <div class="status" id="status">就绪</div>
    </div>
    <hr/>
    链接设备信息
    <hr/>
    <div id="map"></div>
    <br/>
    <hr/>
    <div class="status" id="jl">下注历史记录</div>
    <script>
      const statusEl = document.getElementById('status');
      const jlEl = document.getElementById('jl');
      async function clear(){
        //清空后需要重新启动
        const res = await fetch('/clear', { method: 'POST' ,}).finally(()=>{
          getMap()
        });
      }
      async function send(path,params) {
        statusEl.textContent = `发送中: ${path}`;
        try {
          const res = await fetch(path, { method: 'POST' ,
          headers: {
          "Content-Type": "application/json",
          },
          body: JSON.stringify(params),
          });
          const data = await res.json().catch(() => ({}))
          statusEl.textContent = `已发送: ${path}，响应: ${JSON.stringify(data)}`;
          jlEl.innerHTML = `${jlEl.innerHTML}<br/>已发送: ${path}，${JSON.stringify(params)}响应: ${JSON.stringify(data)}`;
        } catch (err) {
          statusEl.textContent = `发送失败: ${String(err)}`;
          jlEl.innerHTML = `${jlEl.innerHTML}<br/>发送失败: ${path}，${JSON.stringify(params)}失败: ${String(err)}`;
        }
      }
      async function getXzTime(map_key) {
        let path = '/send/xzTime'
        let params = {
          map_key:map_key
        }
        statusEl.textContent = `发送中: ${path}`;
        try {
          const res = await fetch(path, { method: 'POST' ,
          headers: {
          "Content-Type": "application/json",
          },
          body: JSON.stringify(params),
          });
          const data = await res.json().catch(() => ({}))
          statusEl.textContent = `已发送: ${path}，响应: ${JSON.stringify(data)}`;
          jlEl.innerHTML = `${jlEl.innerHTML}<br/>已发送: ${path}，${JSON.stringify(params)}响应: ${JSON.stringify(data)}`;
        } catch (err) {
          statusEl.textContent = `发送失败: ${String(err)}`;
          jlEl.innerHTML = `${jlEl.innerHTML}<br/>发送失败: ${path}，${JSON.stringify(params)}失败: ${String(err)}`;
        }
      }
      function clickAllXz(room) {
        document.querySelectorAll('button[name="'+room+'"]').forEach(btn => btn.click());
      }
      let listItems = [];
      async function getMap(){

            //渲染map到页面
            const mapEl = document.getElementById('map');
            mapEl.innerHTML = '';
            const res = await fetch('/getMap', { method: 'GET' });
            listItems = await res.json().catch(() => ({}));
            console.log(listItems);
            for (const room in listItems) {
                const roomEl = document.createElement('div');
                roomEl.textContent = room;
                for (const item of listItems[room]) {
                    itemElOld = document.getElementById("itemEl"+item.num)
                    if (itemElOld){

                      let getMoneyTime = new Date(item.getMoneyTime*1000).toLocaleTimeString('zh-CN')
                      let setMoneyTime = new Date(item.setMoneyTime*1000).toLocaleTimeString('zh-CN')
                      itemElOld.textContent = `编号：${item.num} ---- 当前余额：${item.money}(刷新时间:${getMoneyTime}) (下注时间:${setMoneyTime})   `;

                    }
                    const itemEl = document.createElement('div');
                    itemEl.id = "itemEl"+item.num
                    const buttonSet = document.createElement('input');
                    const buttonSetLabel = document.createElement('label');
                    buttonSetLabel.textContent = "大"
                    buttonSet.type="radio"
                    buttonSet.name="idr"+item.num
                    const buttonSet2 = document.createElement('input');
                    const buttonSetLabel2 = document.createElement('label');
                    buttonSetLabel2.textContent = "小"
                    buttonSet2.type="radio"
                    buttonSet2.name="idr"+item.num
                    const floatNumberx = document.createElement('input');
                    const floatNumberd = document.createElement('input');
                    floatNumberd.id = "idd"+item.num;
                    floatNumberx.id = "idx"+item.num;
                    //时间戳转时间
                    let getMoneyTime = new Date(item.getMoneyTime*1000).toLocaleTimeString('zh-CN')
                    let setMoneyTime = new Date(item.setMoneyTime*1000).toLocaleTimeString('zh-CN')
                    itemEl.textContent = `编号：${item.num} ---- 当前余额：${item.money}(刷新时间:${getMoneyTime}) (下注时间:${setMoneyTime})   `;

                    const buttonXz = document.createElement('button');
                    buttonXz.textContent = "确认下注"
                    buttonXz.id = "idxz"+item.num
                    buttonXz.name = room
                    buttonXz.addEventListener('click', function () {
                      const num      = this.id.replace('idxz', '');
                      const roomKey  = room;                       // 外层循环的 room
                      const selected = document.querySelector(`input[name="idr${num}"]:checked`);
                      if (!selected) { alert('请选择“大”或“小”'); return; }
                      const text  = selected.nextSibling.textContent.trim(); // "大" / "小"
                      const moneyd = document.getElementById(`idd${num}`).value || "0";
                      const moneyx = document.getElementById(`idx${num}`).value || "0";
                      send('/send/set', { map_key: roomKey, text: text,money:(text==='大'?moneyd:moneyx),num:num});
                    });
                    itemEl.appendChild(buttonSet);
                    itemEl.appendChild(buttonSetLabel);
                    itemEl.appendChild(floatNumberd);
                    itemEl.appendChild(buttonSet2);
                    itemEl.appendChild(buttonSetLabel2);
                    itemEl.appendChild(floatNumberx);
                    itemEl.appendChild(buttonXz);
                    roomEl.appendChild(itemEl);
                }
                const buttonGet = document.createElement('button');
                buttonGet.addEventListener('click', () => send('/send/get',{
                  map_key:room
                }));
                buttonGet.textContent = '房间查询'
                roomEl.appendChild(buttonGet);
                const buttonGet2 = document.createElement('button');
                buttonGet2.addEventListener('click', () => clickAllXz(room));
                buttonGet2.textContent = '下注'
                roomEl.appendChild(buttonGet2);
                const buttonGet3 = document.createElement('button');
                buttonGet3.addEventListener('click', () => getXzTime(room));
                buttonGet3.textContent = '获取时间'
                roomEl.appendChild(buttonGet3);
                mapEl.appendChild(roomEl);
                const hr = document.createElement('hr');
                mapEl.appendChild(hr);
            }

      }

      document.getElementById('btnGet').addEventListener('click', () => send('/send/get',{
        map_key:""
      }));
      document.getElementById('flashPage').addEventListener('click', () => getMap());
    </script>
  </body>
  </html>